﻿namespace BloodlustFury.DataMiner.Business
{
	#region "Using Statements"

	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
	using System.Collections;
	using FileHelpers;
	using System.IO;
	
	#endregion

	public class ModuleList<T> where T : Module, new()
	{
		private List<T> items = new List<T>();

		public String FileName { get; private set; }

		public List<T> Items
		{
			get
			{
				return items;
			}
		}

		internal List<T> ActualItems
		{
			get { return items; }
		}

		public void LoadModules(String file)
		{
			FileHelperEngine engine = new FileHelperEngine(typeof(ModuleFileDataRow));
			ModuleFileDataRow[] data;

			items.Clear();
			FileName = file;

			try
			{
				data = engine.ReadFile(file) as ModuleFileDataRow[];

				foreach (ModuleFileDataRow row in data)
				{
					T module = new T();
					module.X1 = row.X1;
					module.X2 = row.X2;
					module.X3 = row.X3;
					module.X4 = row.X4;
					module.X5 = row.X5;
					module.X6 = row.X6;
					module.X7 = row.X7;
					module.X8 = row.X8;
					module.X9 = row.X9;
					module.X10 = row.X10;
					module.Y = row.Y;

					items.Add(module);
				}
			}
			catch (Exception)
			{
				items.Clear();
				//Try manualing parsing the file.
				this.ManualLoad(file);
			}
		}

		private void ManualLoad(String file)
		{
			using (StreamReader reader = new StreamReader(file))
			{
				String line = reader.ReadLine();
				String[] elements;

				while (reader.Peek() != -1)
				{
					line = reader.ReadLine();

					elements = line.Split(',');

					T module = new T();

					module.X1 = Double.Parse(elements[0]);
					module.X2 = Double.Parse(elements[1]);
					module.X3 = Double.Parse(elements[2]);
					module.X4 = Double.Parse(elements[3]);
					module.X5 = Double.Parse(elements[4]);
					module.X6 = Double.Parse(elements[5]);
					module.X7 = Double.Parse(elements[6]);
					module.X8 = Double.Parse(elements[7]);
					module.X9 = Double.Parse(elements[8]);
					module.X10 = Double.Parse(elements[9]);

					if (elements.Length == 11)
					{
						module.Y = Double.Parse(elements[10]);
					}
					else
					{
						module.Y = -1;
					}

					items.Add(module);
				}
			}
		}
	}
}
